<template>
  <div class="voice-lib">
    <div class="search-wrap">
      <search
        ref="searchItem"
        @add="addCallAudio"
        @refresh="refreshList"
        @search="searchByName"
        :currentPage="currentPage"
        :count="tableData.length || 0"
        :pageSize="tableData.length || 1"
        :forCall="true"
        :isReloadIvr="false"
        :showAdvSearch="false"
        :isShowInput="true"
        :inputTitle="'请输入语音文件名称'"
      >
      </search>
    </div>
    <!--<div style="border-top:1px solid #d9d9d9;">-->
      <!--<el-row :gutter="20" style="padding:6px 10px;margin:0;">-->
        <!--<el-col :span="12">-->
          <!--<el-select size="mini" v-model="PBX" :placeholder="$t('public.pleasePick')" style="width:100%;" @change="changePBX">-->
            <!--<el-option-->
              <!--:label="'全部'"-->
              <!--:value="''">-->
            <!--</el-option>-->
            <!--<el-option-->
              <!--v-for="(item,index) in pbxs"-->
              <!--:label="item.NickName + ' (' +item.PBX + ')'"-->
              <!--:value="item.PBX"-->
              <!--:key="index">-->
            <!--</el-option>-->
          <!--</el-select>-->
        <!--</el-col>-->
        <!--<el-col :span="12">-->
          <!--<el-input-->
            <!--:placeholder="$t('config.channel.enterVoiceFiled')"-->
            <!--class="condition"-->
            <!--v-model="searchContent"-->
            <!--size="mini"-->
            <!--@keyup.enter.native="searchByName"-->
          <!--&gt;-->
            <!--<i-->
              <!--class="el-input__icon el-icon-search"-->
              <!--slot="suffix"-->
              <!--@click="searchByName">-->
            <!--</i>-->
          <!--</el-input>-->
        <!--</el-col>-->
      <!--</el-row>-->
    <!--</div>-->
    <call-audio-table :isSimpleConfig="true" :tableHeader="tableHeader" :tableData="tableData" @resh="commitAndQueryList" @editVoice="editVoice"></call-audio-table>
    <left-slide :title="titleArr[1]" :visible.sync="isShowDetail" :showFooter="false" :width="'450px'">
      <call-audio-detail v-if='isShowDetail' :isSimpleConfig="true" :currentData="currentData" :isRestFrom="isRestFrom" :showBread="showBread" @resh='commitAndQueryList'  @cancle="cancle" :reshAdd="addCallAudio"></call-audio-detail>
    </left-slide>
  </div>
</template>
<script>
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  import search from '../../config/channelConfig/base/search'
  import CallAudioTable from '../../config/channelConfig/telCustomerService/CallAudioTable.vue'
  import CallAudioDetail from '../../config/channelConfig/telCustomerService/CallAudioDetail.vue'
  import {ivrSearch, deepClone} from '@/utils/m7Utils.js'
  export default {
    name: 'voiceAudioLibrary',
    data () {
      return {
        currentPage: 1,    //   当前页
        tableHeader: [
          {prop: 'DisplayName', label: this.$t('config.channel.voiceFiledName')},
          {prop: 'Memo', label: this.$t('config.channel.voiceFiledExplain')},
          {prop: 'UpdateTime', label: this.$t('config.channel.lastUpdateTime')},
          {prop: 'PBX', label: 'PBX'},
          {prop: '', label: this.$t('sms.operate')}
        ],                        //   自定义 表头
        isShowDetail: false, //   是否要展示右边
        tableData: [],
        showBread: 'addVoice',
        currentData: {},
        emptyFrom: {Account: this.$store.state.session.account.account, DisplayName: '', Filename: '', Memo: '', PBX: this.$store.state.session.user.pbx, SoundType: 'normal', UpdateTime: '', UpdateUser: '', fileUrl: '', _id: ''},
        pbxs: [],
//        PBX: '',
        searchContent: '',
        ivrSoundList: [],
        isRestFrom: 0,
        titleArr: [this.$t('config.channel.voiceLibrary'), this.$t('config.channel.addVoice')],
        currentPbxList: [], // 当前的pbx的数据
        oldPBX: '',   //   用来判断页面再次激活时  pbx是否切换过
        currentPBX: this.$store.state.session.user.pbx
      }
    },
    components: {
      leftSlide,
      search,
      CallAudioTable,
      CallAudioDetail
    },
    methods: {
      changePBX (pbx) {
        this.isShowDetail = false
        this.queryList('', pbx, 'searchPbx')
      },
      searchByName (val) { // 根据名字本地搜索
        this.isShowDetail = false
        this.searchContent = val
        let searchResult = ivrSearch(this.ivrSoundList, this.searchContent, ['DisplayName']) || []
        this.tableData = searchResult
      },
      cancle () {
        this.isShowDetail = false
      },
      commitAndQueryList (pbx) {
        this.currentPBX = pbx
        this.searchContent = ''
        this.$refs.searchItem.searchContent = ''
        this.queryList('commit', this.PBX, 'searchPbx')
      },
      refreshList () {
        this.searchContent = ''
        this.$refs.searchItem.searchContent = ''
        this.queryList('', this.PBX, 'searchPbx')
      },
      queryList (commitFlag, pbx, searchPbx) { // 获取列表或者是刷新列表
        let data = {}
        data.Account = this.$store.state.session.account.account
        if (pbx) {
          data.PBX = pbx
        }
        this.$store.dispatch('querySound', data).then(resp => {
          if (resp && resp.success) {
            this.isShowDetail = false
            this.ivrSoundList = resp.list
            this.getNewAudioData(resp.list, pbx, searchPbx)
            if (commitFlag) {
              this.$store.commit('SET_IVRMAP_DETAIL', {PBX: this.currentPBX, typeName: 'ivr_sound', data: this.ivrSoundList || [], flag: 'data', node: this})
//              this.currentPBX = this.$store.state.session.user.pbx
              console.log(this.ivrSoundList)
            }
          } else {
            this.$message.error(this.$t('查询失败！'))
          }
        })
      },
      getNewAudioData (data, pbx, searchPbx) {
        let newArr = []
        this.currentPbxList = []
        for (let i = 0; i < data.length; i++) {
          if (data[i].PBX === this.currentPBX) {
            this.currentPbxList.push(data[i])
          }
          let soundFileName = ''
          let fileUrl = ''
          if (!data[i].Memo || data[i].Memo === ' ') {
            data[i].Memo = '--'
            data[i].MemoFlag = true
          }
          if (data[i].IsQiniuMusic && data[i].IsQiniuMusic === 'yes') {
            soundFileName = data[i].Filename.substring(0, data[i].Filename.indexOf('.'))
            fileUrl = data[i].QiniuMusicUrl.replace('@', '=/')
            let tmpTag = false
            if (document.location.protocol === 'https:') {
              tmpTag = true
            }
            if (tmpTag) {
              fileUrl = fileUrl.replace('http', 'https')
            }
          } else {
            soundFileName = data[i].Filename.substring(0, data[i].Filename.indexOf('.'))
            let loginToken = window.sessionStorage.getItem('loginToken')
            fileUrl = './' + 'fileDownload/?sessionId=' + this.$store.state.session.sessionId + '&fileId=' + soundFileName + '&loginToken=' + loginToken
          }
          data[i].fileUrl = fileUrl
          if (searchPbx === 'searchPbx') { // 更改pbx时
            if (pbx) {
              if (data[i].PBX === pbx) {
                newArr.push(data[i])
              }
            } else { // 全选时
              newArr.push(data[i])
            }
          }
        }
        if (searchPbx === 'searchPbx') { // 先根据pbx筛选，然后根据名字再筛选
          let searchResult = ivrSearch(newArr, this.searchContent, ['DisplayName']) || []
          this.tableData = searchResult
        } else {
          this.tableData = data
        }
      },
      addCallAudio () { // 添加录音
        this.isShowDetail = true
        this.showBread = 'addVoice'
        this.titleArr.splice(1, 1, this.$t('config.channel.addVoice'))
        this.currentData = deepClone(this.emptyFrom)
        this.isRestFrom = Math.random()
      },
      editVoice (val) { // 修改录音
        if (val.Memo === '--' && val.MemoFlag) {
          val.Memo = ''
        }
        this.currentData = deepClone(val)
        this.isShowDetail = true
        this.showBread = 'editVoice'
        this.titleArr.splice(1, 1, this.$t('config.channel.editVoice'))
        this.isRestFrom = Math.random()
      }
    },
    computed: {
      PBX () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    watch: {
      PBX () {
        let routerName = this.$route.meta.title
        if (routerName === 'voiceLibraryManage') {
          this.changePBX(this.PBX)
        }
      }
    },
    deactivated () {
      this.oldPBX = this.PBX
    },
    activated () {
      if (this.oldPBX !== this.PBX) {
        this.changePBX(this.PBX)
      }
    },
    beforeMount () {
      this.changePBX(this.PBX)
    }
  }
</script>
<style lang="stylus" scoped>
  .voice-lib
    padding 20px
  .search-wrap
    padding 6px
    border 1px solid #E7E7EB
    border-bottom none
</style>
